﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ManiaDown.SayoApi;

namespace ManiaDown
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
            dataGridView1.Columns.Add("Title", "标题");
            dataGridView2.Columns.Add("Title", "标题");
            dataGridView2.Columns.Add("Progress", "下载进度");
            SayoApi.SayoApi.DownloadProgressChanged += SayoApi_DownloadProgressChanged;
        }

        private void SayoApi_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
        {
            UpdateList(sender, e);
        }

        private delegate void FlushList(object sender, System.Net.DownloadProgressChangedEventArgs e);

        private void UpdateList(object sender, System.Net.DownloadProgressChangedEventArgs e)
        {
            if (dataGridView1.InvokeRequired)//等待异步
            {
                FlushList fl = new FlushList(UpdateList);
                Invoke(fl);
            }
            else
            {
                var map = SayoApi.SayoApi.DownloadListDic[sender as WebClient];
                for(var i=0;i<dataGridView2.Rows.Count;i++)
                {
                    if (dataGridView2.Rows[i].Cells["Title"].Value == map)
                    {
                        dataGridView2.Rows[i].Cells["Progress"].Value = e.ProgressPercentage;
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var maps = SayoApi.SayoApi.GetBeatmapList(new BeatmapListQuery(Modes.Mania, MapStatus.Ranked, new AdvanceLimit(new SayoApi.Range(4, 6))));
            foreach(var map in maps)
            {
                dataGridView1.Rows.Add(map);
            }
            dataGridView1.AutoResizeColumns();


            foreach (var map in maps)
            {
                dataGridView2.Rows.Add(map);
            }

            foreach (var map in maps)
            {
                SayoApi.SayoApi.DownloadBeatmap(map);
            }
        }
    }
}
